<?php
/**
 * Created by PhpStorm.
 * User: luohuaming
 * Date: 2016/8/4
 * Time: 10:50
 */

namespace Admin\Model;


use Think\Model;

class PrivilegeModel extends Model
{
    /**
     * @param $map 查询条件
     * @param  $pagenumber =1 页号
     * @param $pagesize =20 页面大小
     * @return mixed
     */
    public function getByConditionPage($map = null, $pagenumber = 1, $pagesize = 20)
    {
        $startno = ($pagenumber - 1) * $pagesize;
        $limit = $startno . ',' . $pagesize;//每页的数据数和内容$limit
        $list = $this->table('t_privilege')->join('LEFT JOIN t_privilege as p ON t_privilege.parent_id = p.id')
            ->where($map)->field('t_privilege.* , p.name as parent_name')
            ->order('id desc')->limit($limit)->select();
        return $list;
    }

    public function getTree()
    {
        $data = $this->getAll();
        return $this->_reSort($data);
    }

    private function _reSort($data, $parent_id = 0, $level = 0, $isClear = TRUE)
    {
        static $ret = array();
        if ($isClear)
            $ret = array();
        foreach ($data as $k => $v) {
            if ($isClear) $v['level'] = '';
            if ($v['parent_id'] == $parent_id) {
                $v['level'] .= str_repeat('-', 4 * $level);
                $ret[] = $v;
                $this->_reSort($data, $v['id'], $level + 1, FALSE);
            }
        }
        return $ret;
    }

    public function getAll()
    {
        $list = $this->query('SELECT t_privilege.*,p.name as parent_name FROM `t_privilege` LEFT JOIN t_privilege as p ON t_privilege.parent_id = p.id');
        return $list;
    }

    public function getTopPrivilegeList()
    {
        $list = $this->where('parent_id = 0')
            ->select();
        for ($i = 0; $i < count($list); $i++) {
            $list[$i]['children'] = $this->getListByTop($list[$i]['id']);
        }
        return $list;
    }

    //通过父id获取所有子id
    public function getListByTop($parent_id)
    {
        $where['parent_id'] = ':parent_id';
        $list = $this->where($where)->bind(':parent_id', $parent_id)->select();
        return $list;
    }

    /**
     * 通过管理员Id获取权限列表
     * @param $adminId 管理员id
     * @return 取权限列表
     */
    public function getPrivilegeListByAdmin($adminId)
    {
        $roleIds = $this->getRoleIdsByAdmin($adminId);
        $list = $this->getPrivilegeListByRoleIds($roleIds);
        return $list;
    }

    /**通过角色ids获取权限列表
     * @param $roleIds 角色ids
     * @param $where =null 条件
     * @return mixed 权限列表
     */
    private function getPrivilegeListByRoleIds($roleIds, $where = null)
    {
        $ids = '';
        foreach ($roleIds as $key => $value) {
            if (count($roleIds) == $key + 1)
                $ids .= $value['id'];
            else
                $ids .= $value['id'] . ',';
        }
        $where['r.id'] = array('in', $ids);
        $list = $this->table('t_privilege p')->join('LEFT JOIN t_role_privilege rp ON rp.pri_id = p.id')
            ->join('LEFT JOIN  t_role r on r.id = rp.role_id')
            ->where($where)->field('p.*')->order('p.id desc')->group('p.id')->select();
        return $list;
    }

    /**通过URL和用户id判断是否有访问权限
     * @param $url 权限URL
     * @param $adminId 管理员id
     * @return true有访问权限 false 没有访问权限
     */
    public function getPrivilegeByUrlAndAdmin($url, $adminId)
    {
        $where['p.url'] = array('like', '%' . $url . '%');
        $where['ar.admin_id'] = $adminId;
        $count = $this->table('t_privilege p')->join('LEFT JOIN t_role_privilege rp ON rp.pri_id = p.id')
            ->join('LEFT JOIN  t_admin_role ar on ar.role_id = rp.role_id')
            ->where($where)->count();
        if ($count >= 1) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 获取管理员在界面中显示的权限列表
     * @param $adminId  管理员id
     * @return mixed 权限列表
     */
    public function getPrivilegeMenuListByAdmin($adminId)
    {
        $roleIds = $this->getRoleIdsByAdmin($adminId);
        $parentList = $this->getParentList($roleIds);
        for ($i = 0; $i < count($parentList); $i++) {
            $where['parent_id'] = $parentList[$i]['id'];
            $where['p.is_menu'] = 1;
            $parentList[$i]['children'] = $this->getPrivilegeListByRoleIds($roleIds, $where);
        }
        return $parentList;
    }

    /**
     * @param $roleIds
     * @return mixed
     */
    private function getParentList($roleIds)
    {
        $where['is_menu'] = 1;//在菜单栏中显示的
        $where['parent_id'] = 0;//根节点
        $parentList = $this->getPrivilegeListByRoleIds($roleIds, $where);
        return $parentList;
    }

    /**通过管理员Id获取所属角色Ids
     * @param $adminId 管理员Id
     * @return mixed 所属角色Ids
     */
    private function getRoleIdsByAdmin($adminId)
    {
        $where['a.id'] = ':id';
//        $where['a.id'] = $adminId;
        $bind[':id'] = array($adminId, \PDO::PARAM_INT);
        $RoleModel = D('Role');
        $roleIds = $RoleModel->join('LEFT JOIN t_admin_role ar on ar.role_id = t_role.id')
            ->join('LEFT JOIN t_admin a on a.id = ar.admin_id')
            ->where($where)->bind($bind)
            ->field('t_role.id')->select();
        return $roleIds;
    }
}